
package com.projectxxxxxxxxxx;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import android.app.Application;
import android.bluetooth.BluetoothAdapter;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.media.AudioManager;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.wifi.WifiManager;
import android.os.BatteryManager;
import android.util.Log;
import android.widget.Toast;

import com.projectxxxxxxxxxx.report.ErrorReporter;
import com.projectxxxxxxxxxx.widget.RoboAppWidgetProvider;
import com.projectxxxxxxxxxx.widget.RoboAppWidgetProvider4x4;
import com.projectxxxxxxxxxx.widget.WidgetManager;
import com.projectxxxxxxxxxx.widget.WidgetView;

public class RoboApplication extends Application implements SensorEventListener {

    private String myStringState;
    private Integer myIntState;

    private WidgetManager widgetManager;
    private WidgetView widgetView;

    private RoboAppWidgetProvider commonReciever;

    private static RoboApplication instance = null;

	private SensorManager sensorManager;

    public RoboApplication() {
        instance = this;
        Log.i(getClass().toString(), getMethodName());
    }

    public static Context getInstance() {
        if (null == instance) {
            instance = new RoboApplication();
        }
        return instance;
    }

    public static String getStringFromId(int id) {
        return getInstance().getString(id);
    }

	private void printDimens(double coef) {

		Pattern pattern = Pattern.compile("\\d+");
		BufferedReader r = new BufferedReader(new InputStreamReader(getResources().openRawResource(R.raw.dimens)));

		String result = "";

		String line;
		int lineCount = 0;
		try {
			while ((line = r.readLine()) != null) {
				lineCount++;
				
				if (lineCount > 1) {
					Matcher matcher = pattern.matcher(line);
					int start = 0;
					while (matcher.find(start)) {
						String value = line.substring(matcher.start(), matcher.end());
						int number = Integer.parseInt(value);
	
						if (number > 5) {
							// Log.e(getClass().toString(), value);
							result += line.substring(start, matcher.start());
							result += Math.round(number * coef);

						} else {
							result += line.substring(start, matcher.end());
						}
						start = matcher.end();
					}

					result += line.substring(start, line.length());

				} else {
					result += line;
				}
			}

			int maxLogSize = 1000;
			for (int i = 0; i <= result.length() / maxLogSize; i++) {
				int start = i * maxLogSize;
				int end = (i + 1) * maxLogSize;
				end = end > result.length() ? result.length() : end;
				Log.v(getClass().toString(), result.substring(start, end));
			}

		} catch (NumberFormatException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}



	}

    @Override
    public void onCreate() {
        super.onCreate();
        
		Log.e(getClass().toString(), "MDPI");
		Log.e(getClass().toString(),
				"-----------------------------------------------------------------------------------");
		printDimens(0.90);

		Log.e(getClass().toString(), "XHDPI");
		Log.e(getClass().toString(),
				"-----------------------------------------------------------------------------------");
		printDimens(2.00);

		Log.e(getClass().toString(), "HDPI");
		Log.e(getClass().toString(),
				"-----------------------------------------------------------------------------------");
		printDimens(1.50); // hdpi

		Log.e(getClass().toString(), "LDPI");
		Log.e(getClass().toString(),
				"-----------------------------------------------------------------------------------");
		printDimens(0.75); // пока не надо мб
      
        Thread.setDefaultUncaughtExceptionHandler(new ErrorReporter());
        Log.i(getClass().toString(), getMethodName());

        
		setToggleListner();
        widgetManager = new WidgetManager(this);
        widgetView = new WidgetView();

		// startService(new Intent(this, GetInfoService.class));
		// startAlarmManager();

		// Toast.makeText(this, "Netcounter service has been lauched", Toast.LENGTH_LONG).show();
		// Intent bootActivityIntent = new Intent(this, mService1.class);
		// bootActivityIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
		// startService(bootActivityIntent);
        
        // receiver for update indicators and action light with all actions
        commonReciever = new RoboAppWidgetProvider4x4();
        
        IntentFilter intentfilter = new IntentFilter();
        intentfilter.addAction(Intent.ACTION_BATTERY_CHANGED);
        intentfilter.addAction("android.intent.action.HEADSET_PLUG");
        registerReceiver(commonReciever, intentfilter);

        
        IntentFilter ifilter = new IntentFilter(Intent.ACTION_BATTERY_CHANGED);
        Intent batteryStatus = registerReceiver(null, ifilter);
        int chargePlug = batteryStatus.getIntExtra(BatteryManager.EXTRA_PLUGGED, -1);
        boolean usbCharge = chargePlug == BatteryManager.BATTERY_PLUGGED_USB;
        boolean acCharge = chargePlug == BatteryManager.BATTERY_PLUGGED_AC;
        if(usbCharge){
	   		 widgetView.renderUSBIcon(true);
	   		 widgetView.renderPOWERIcon(true);
	   	 } else if(acCharge){
	   		 widgetView.renderUSBIcon(false);
	   		 widgetView.renderPOWERIcon(true);
	   	 } else {
	   		 widgetView.renderUSBIcon(false);
	   		 widgetView.renderPOWERIcon(false);
	   	 }
        
        // for to start update action light
        final Intent intent = new Intent(Constants.ACTION_UPDATE_ACTION_LIGHT);
        sendBroadcast(intent);

		sensorManager = (SensorManager) getSystemService(SENSOR_SERVICE);
		sensorManager.registerListener(this, sensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER),
				SensorManager.SENSOR_DELAY_NORMAL);
    } 
    

	@Override
	public void onSensorChanged(SensorEvent event) {

		int value = 0 ;
		int valueVertical = 0;
		if (event.sensor.getType() == Sensor.TYPE_ACCELEROMETER) {
			// Log.e(getClass().toString(), "onSensorChanged " + event.values[0] + "   " + event.values[1] + "  "
			// + event.values[2]);
			if (event.values[0] > 4) {
                value = -4;
            } else if (event.values[0] < -4) {
				value = 4;
			} else if (event.values[0] > 3) {
                value = -3;
            } else if (event.values[0] < -3) {
				value = 3;
			} else if (event.values[0] > 2) {
                value = -2;
            } else if (event.values[0] < -2) {
				value = 2;
			} else if (event.values[0] > 1) {
                value = -1;
            } else if (event.values[0] < -1) {
				value = 1;
			} else {
				value = 0;
			}
			
			if(event.values[1] < 4  ) {
				valueVertical = -1;
			} else if(event.values[1] > 7  ) {
				valueVertical = 1;
			} else {
				valueVertical = 0;
			}

			if (value != WidgetView.EYES || valueVertical != WidgetView.EYES_VERTICAL) {
				WidgetView.EYES = value;
				WidgetView.EYES_VERTICAL = valueVertical;
				 Intent intent = new Intent(Constants.ACTION_UPDATE_ACTION_EYES);
				 sendBroadcast(intent);
			}
			
		        
		}
	}

	@Override
	public void onAccuracyChanged(Sensor sensor, int accuracy) {
		// Log.e(getClass().toString(), "onAccuracyChanged " + accuracy);
	}

	private void setToggleListner() {
		IntentFilter intentfilter = new IntentFilter();

		intentfilter.addAction(ConnectivityManager.CONNECTIVITY_ACTION);
		intentfilter.addAction("android.intent.action.ANY_DATA_STATE");
		// <uses-permission android:name="android.permission.READ_PHONE_STATE"/>
		intentfilter.addAction(android.telephony.TelephonyManager.ACTION_PHONE_STATE_CHANGED);
		intentfilter.addAction(Intent.ACTION_DOCK_EVENT);

		intentfilter.addAction(Intent.ACTION_SCREEN_OFF);
		intentfilter.addAction(Intent.ACTION_SCREEN_ON);

		intentfilter.addAction(WifiManager.WIFI_STATE_CHANGED_ACTION);
		intentfilter.addAction(BluetoothAdapter.ACTION_STATE_CHANGED);
		intentfilter.addAction(AudioManager.RINGER_MODE_CHANGED_ACTION);
		intentfilter.addAction("android.location.GPS_ENABLED_CHANGE");

        // intentfilter.addAction(Intent.ACTION_MEDIA_MOUNTED);
        // intentfilter.addAction(Intent.ACTION_MEDIA_UNMOUNTED);

        // intentfilter.addAction(Intent.ACTION_POWER_CONNECTED);
        // intentfilter.addAction(Intent.ACTION_POWER_DISCONNECTED);

		registerReceiver(toggleStateChangedReceiver, intentfilter);
		//

		// GpsStatus.Listener onGpsStatusChange = new GpsStatus.Listener() {
		// @Override
		// public void onGpsStatusChanged(int event) {
		// if (event == GpsStatus.GPS_EVENT_SATELLITE_STATUS) {
		// Toast.makeText(getInstance(), " GPS ", Toast.LENGTH_LONG).show();
		// // GpsStatus status = mLocManager.getGpsStatus(null);
		// // Iterable<GpsSatellite> sats = status.getSatellites();
		// // Check number of satellites in list to determine fix state
		// }
		// Toast.makeText(getInstance(), " GPS  2 ", Toast.LENGTH_LONG).show();
		// }
		// };
		// LocationManager locMgr = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
		// locMgr.addGpsStatusListener(onGpsStatusChange);
	}

	private final BroadcastReceiver toggleStateChangedReceiver = new BroadcastReceiver() {

		@Override
		public void onReceive(Context context, Intent intent) {

			String action = intent.getAction();


			// intentfilter.addAction("android.location.GPS_ENABLED_CHANGE");

			if (action.equals(ConnectivityManager.CONNECTIVITY_ACTION)) {
				//Toast.makeText(getInstance(), " CONNECTIVITY_ACTION event ", Toast.LENGTH_LONG).show();
			} else if (action.equals("android.intent.action.ANY_DATA_STATE")) {
				//Toast.makeText(getInstance(), " ANY_DATA_STATE event ", Toast.LENGTH_LONG).show();
			} else if (action.equals(android.telephony.TelephonyManager.ACTION_PHONE_STATE_CHANGED)) {
				// <uses-permission android:name="android.permission.READ_PHONE_STATE"/>
				//Toast.makeText(getInstance(), " ACTION_PHONE_STATE_CHANGED event ", Toast.LENGTH_LONG).show();
			} else if (action.equals(Intent.ACTION_DOCK_EVENT)) {
				//Toast.makeText(getInstance(), " ACTION_DOCK_EVENT event ", Toast.LENGTH_LONG).show();
			} else if (action.equals(Intent.ACTION_SCREEN_OFF)) {
				///Toast.makeText(getInstance(), " ACTION_SCREEN_OFF event ", Toast.LENGTH_LONG).show();
			} else if (action.equals(Intent.ACTION_SCREEN_ON)) {
				//Toast.makeText(getInstance(), " ACTION_SCREEN_ON event ", Toast.LENGTH_LONG).show();
			} else if (action.equals(Intent.ACTION_MEDIA_MOUNTED)) {
				//Toast.makeText(getInstance(), " ACTION_MEDIA_MOUNTED event ", Toast.LENGTH_LONG).show();
			} else if (action.equals(Intent.ACTION_MEDIA_UNMOUNTED)) {
				//Toast.makeText(getInstance(), " ACTION_MEDIA_UNMOUNTED event ", Toast.LENGTH_LONG).show();
			} else if (action.equals(Intent.ACTION_POWER_CONNECTED)) {
				//Toast.makeText(getInstance(), " ACTION_POWER_CONNECTED event ", Toast.LENGTH_LONG).show();
			} else if (action.equals(Intent.ACTION_POWER_DISCONNECTED)) {
				//Toast.makeText(getInstance(), " ACTION_POWER_DISCONNECTED event ", Toast.LENGTH_LONG).show();
			} else if (action.equals(WifiManager.WIFI_STATE_CHANGED_ACTION)) {

				Toast.makeText(getInstance(), " WIFI event ", Toast.LENGTH_LONG).show();

				if (true) {
					return;
				}

				int extraWifiState = intent.getIntExtra(WifiManager.EXTRA_WIFI_STATE, WifiManager.WIFI_STATE_UNKNOWN);

				switch (extraWifiState) {
				case WifiManager.WIFI_STATE_DISABLED:
				case WifiManager.WIFI_STATE_DISABLING:
					// enableUI(false);
					break;
				case WifiManager.WIFI_STATE_ENABLED:
					ConnectivityManager conMan = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
					while (conMan.getActiveNetworkInfo() == null
							|| conMan.getActiveNetworkInfo().getState() != NetworkInfo.State.CONNECTED) {
						try {
							Thread.sleep(500);
						} catch (InterruptedException e) {
							e.printStackTrace();
						}
					}
					// update();

					break;
				case WifiManager.WIFI_STATE_ENABLING:
					break;
				case WifiManager.WIFI_STATE_UNKNOWN:
					break;
				}
			} else if (action.equals(BluetoothAdapter.ACTION_STATE_CHANGED)) {
				//Toast.makeText(getInstance(), " BLUETOOTH event ", Toast.LENGTH_LONG).show();
			} else if (action.equals(AudioManager.RINGER_MODE_CHANGED_ACTION)) {
				//Toast.makeText(getInstance(), " SILENT event", Toast.LENGTH_LONG).show();
				AudioManager am = (AudioManager) getSystemService(Context.AUDIO_SERVICE);
				switch (am.getRingerMode()) {
				case AudioManager.RINGER_MODE_SILENT:
					Log.i("MyApp", "Silent mode");
					break;
				case AudioManager.RINGER_MODE_VIBRATE:
					Log.i("MyApp", "Vibrate mode");
					break;
				case AudioManager.RINGER_MODE_NORMAL:
					Log.i("MyApp", "Normal mode");
					break;
				}
			} else if (action.equals("android.location.GPS_ENABLED_CHANGE")) {

				//Toast.makeText(getInstance(), " GPS_ENABLED_CHANGE event ", Toast.LENGTH_LONG).show();
			}
			// else if (action.equals(Intent.ACTION_CONFIGURATION_CHANGED)) {
			//
			// Toast.makeText(getInstance(), "ACTION_CONFIGURATION_CHANGED ", Toast.LENGTH_LONG).show();
			// }
		}
	};

    @Override
    public Object getSystemService(String name) {
        return super.getSystemService(name);
    }

    public static String getMethodName() {
        final int depth = 2;
        final StackTraceElement[] ste = Thread.currentThread().getStackTrace();
        return ste[1 + depth].getMethodName();
    }

    public void startAlarmManager() {
    }

    public void reloadWidgetModel() {
        // widgetManager.requestReload();
    }

    public WidgetManager getWidgetManager() {
        return widgetManager;
    }

    public WidgetView getWidgetView() {
        return widgetView;
    }
}









